package com.whales.lms.rms.web.service;

import java.util.List;

import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import com.whales.lms.rms.web.model.ManualVO;
import com.whales.shared.exception.BaseException;
import com.whales.shared.model.CommonVO;
import com.whales.shared.service.GenericService;
import com.whales.shared.util.FileUtil;

@Service
public class ManualService extends GenericService<ManualVO, ManualVO> {
	private final String SAVE_FILE_PATH = "C:\\file\\man";
	
	@Override
	public int create(ManualVO manualVO) throws Exception{
		MultipartFile multipartFile = manualVO.getManualFile();
		String fileName = multipartFile.getOriginalFilename();
        String saveFilePath = SAVE_FILE_PATH + "\\" + manualVO.getId() + "\\" + fileName;
        
        manualVO.setParentId(manualVO.getId());
        manualVO.setSepType("HW");
        manualVO.setFileName(fileName);
        manualVO.setSvrPath(saveFilePath);
        //중복파일 체크
        if(this.invalidFile(manualVO)){
        	throw new BaseException(super.getMessage("rms.msg.exitsDuplicatedFile")); //"동일한 파일이 존재합니다."
        }
        // 파일 저장
        if(!FileUtil.saveFile(multipartFile, saveFilePath)){
            throw new BaseException(super.getMessage("rms.msg.foundErrorDuringSavingFile"));//"파일 저장시 오류가 발생하였습니다."
        }
        return super.create("manual.createManual", manualVO);
	}
	
	@Override
	public int delete(ManualVO manualVO) throws Exception {
		ManualVO deleteManualVO = this.findInfo(manualVO);
		int deleteCnt = super.delete("manual.deleteManualById", manualVO);
		FileUtil.removeFile(deleteManualVO.getSvrPath());
		return deleteCnt;
	}
	
	public int deleteByParentId(CommonVO vo) throws Exception{
		ManualVO manualVO = new ManualVO();
		manualVO.setParentId(vo.getId());
		int deleteCnt = this.commonDao.delete("manual.deleteManualByParentId", manualVO);
		List<ManualVO> deleteManualList = this.getManualByParentId(manualVO);
		for (ManualVO deleteManualVO : deleteManualList) {
			FileUtil.removeFile(deleteManualVO.getSepType());
			
		}
		FileUtil.deleteDirectory(SAVE_FILE_PATH + "\\" + vo.getId());
		return deleteCnt;
	}
	
	@Override
	public ManualVO findInfo(ManualVO manualVO) throws Exception{
		return super.findInfo("manual.getManualById", manualVO);
	}
	
	@SuppressWarnings("unchecked")
	public List<ManualVO> getManualByParentId(ManualVO vo) throws Exception {
		return this.commonDao.findList("manual.getManualByParentId", vo);
	}
	
	private boolean invalidFile(ManualVO manualVO) throws Exception{
		if(this.commonDao.findList("manual.getSameFileNameListByParentId",manualVO).size() > 0){
			return true;
		}
		return false;
	}
}
